package com.bcx.wind.workflow.db.tran;

import com.bcx.wind.workflow.entity.WindTask;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 工作流事务管理器
 *
 * @author zhanglei
 */
public class WindTransactionManager {

    /**
     * 当前线程连接
     */
    private ThreadLocal<Connection> connections = new ThreadLocal<>();

    private WindTransactionManager(){}

    private static class LoaderTrans{
        private static WindTransactionManager manager = new WindTransactionManager();
    }

    public static WindTransactionManager getInstance(){
        return LoaderTrans.manager;
    }

    public void setConnection(Connection connection){
        this.connections.set(connection);
    }

    public void removeConnection(){
        connections.remove();
    }

    public Connection  getConnection(){
        return this.connections.get();
    }

    /**
     * 提交
     */
    public  void commit(){
        Connection connection = getInstance().connections.get();
        if(connection != null){
            try {
                connection.commit();
                this.removeConnection();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 回滚
     */
    public  void rollback(){
        Connection connection = getInstance().connections.get();
        if(connection != null){
            try {
                connection.rollback();
                this.removeConnection();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
